const setCookie = require("set-cookie-parser");

const userAgent =
  "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36 Edg/117.0.2045.36";

function compsiteUrl(baseUrl, params) {
  // 解析基本URL
  const url = new URL(baseUrl);

  // url中本来包含的参数
  const urlParams = new URLSearchParams(url.searchParams);

  // 附加的参数
  const queryParams = new URLSearchParams(params);

  // 合并两个 URLSearchParams 对象
  for (const [key, value] of queryParams) {
    urlParams.append(key, value);
  }

  // 将参数字符串附加到基本URL的search部分
  url.search = urlParams;

  return url.toString();
}

// 会话id缓存
var cacheSessionId = undefined;

async function post(url, formData) {
  const sessionId = await getSessionId();

  const resp = await fetch(url, {
    method: "POST",
    //redirect: "manual",
    credentials: "include",
    headers: {
      "User-Agent": userAgent,
      cookie: `JSESSIONID=${sessionId}`,
    },
    body: formData,
  });

  const respContent = await resp.text();
  return respContent;
}

async function postJson(url, formData) {
  const content = await post(url, formData);
  const obj = JSON.parse(content);
  return obj;
}

async function get(baseUrl, params) {
  const url = compsiteUrl(baseUrl, params);

  const sessionId = await getSessionId();

  const resp = await fetch(url, {
    //redirect: "manual",
    credentials: "include",
    headers: {
      "User-Agent": userAgent,
      cookie: `JSESSIONID=${sessionId}`,
    },
  });

  const respContent = await resp.text();
  return respContent;
}

async function getJson(baseUrl, params) {
  const content = await get(baseUrl, params);
  const obj = JSON.parse(content);
  return obj;
}

async function getSessionId() {
  if (cacheSessionId) return cacheSessionId;

  const resp = await fetch(
    "https://kyfw.12306.cn/otn/leftTicket/init?linktypeid=dc",
    {
      // redirect: "manual",
      credentials: "include",
      headers: {
        "User-Agent": userAgent,
        // cookie: `JSESSIONID=${sessionId}`,
      },
    }
  );

  // 解析 cookie
  const cookies = setCookie.parse(resp, {
    decodeValues: true,
  });

  // 取得 token 对应的cookie
  const tokenCookie = cookies.find((e) => e.name == "JSESSIONID");
  if (!tokenCookie) {
    console.log("获取会话id失败");
    return false;
  }

  console.log(JSON.stringify(tokenCookie, null, 2));

  // 保存会话id
  cacheSessionId = tokenCookie.value;
  return cacheSessionId;
}

module.exports = {
  post,
  postJson,
  get,
  getJson,
  getSessionId,
};
